import React, { useEffect } from 'react'
import { Button, Checkbox, Form, Input, Card, Space, message } from 'antd'
import { useNavigate, useParams } from 'react-router-dom'
import {
  reqAddHospitalSet,
  reqGetHospitalSet,
  reqUpdateHospitalSet,
} from '@api/hospital/hospitalSet'
import { IAddParams } from '@api/hospital/hospitalSet/model/hospitalSetTypes'

export default function AddOrUpdateHospitalSet() {
  const [form] = Form.useForm()
  const { id } = useParams()
  const navigate = useNavigate()

  useEffect(() => {
    async function fetch() {
      const result = await reqGetHospitalSet(id as string)
      // console.log(result)
      form.setFieldsValue(result)
    }
    // 发送请求获取要修改的医院数据
    if (id) {
      // 有id,证明是修改,则发送请求获取数据
      fetch()
    }
  }, [])

  const onFinish = async (values: IAddParams) => {
    if (id) {
      values.id = id
      await reqUpdateHospitalSet(values)
    } else {
      // console.log('Success:', values)
      await reqAddHospitalSet(values)
    }
    navigate(-1)
    // 提示用户
    message.success(id ? '修改成功' : '添加成功')
  }
  return (
    <Card>
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 22 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[{ required: true, message: '请填写医院名称' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="医院编码"
          name="hoscode"
          rules={[{ required: true, message: '请填写医院编码' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="api基础路径"
          name="apiUrl"
          rules={[{ required: true, message: '请填写apiUrl' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="联系人名称"
          name="contactsName"
          rules={[{ required: true, message: '请填写联系人名称' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="联系人手机"
          name="contactsPhone"
          rules={[
            {
              required: true,
              message: '请正确添写手机号',
              pattern: /^1[3-9]\d{9}$/,
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 2, span: 16 }}>
          <Space>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
            <Button type="default">返回</Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  )
}
